package com.itheima.travel.web;

import com.itheima.travel.pojo.User;
import com.itheima.travel.service.UserService;
import com.itheima.travel.utils.ServiceFactory;
import com.itheima.travel.web.base.BaseServlet;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@WebServlet("/loginServlet")
public class UserServlet extends BaseServlet {
    public void userLogin(HttpServletRequest request, HttpServletResponse response)  {
        try {
            Map<String, String[]> map = request.getParameterMap();
            User user = new User();
            BeanUtils.populate(user,map);
            UserService service=(UserService)ServiceFactory.getService("LoginService");
            User u=service.userLogin(user);
            System.out.println("u = " + u);
            if (u==null){
                //登录失败
                request.setAttribute("msg","用户名或者密码错误");
                request.getRequestDispatcher("/login.jsp").forward(request,response);
            }else{
                //登陆成功
                HttpSession session = request.getSession();
                session.setAttribute("user",u);
                response.sendRedirect("/index.jsp");

            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

}
